//
//  main.cpp
//  CH24_01_Example1
//
//  Created by Ge Jian Feng on 14-5-18.
//  Copyright (c) 2014年 Ge Jian Feng. All rights reserved.
//

#include <iostream>

#include <cstdio>
#include <cstring>

#ifdef __cplusplus
extern "C" {
#endif
    
#include "Lua/lua.h"
#include "Lua/luaconf.h"
#include "Lua/lualib.h"
#include "Lua/lauxlib.h"
    
#ifdef __cplusplus
}
#endif

void error(lua_State *L, const char *fmt, ...);

int main(int argc, const char * argv[])
{
    char buff[256];
    int errorCode;
    
    // Open Lua
    lua_State *L = luaL_newstate();
    
    // Load System Library
    luaL_openlibs(L);
    
    while (fgets(buff, sizeof(buff), stdin) != NULL) {
        errorCode = luaL_loadbuffer(L, buff, strlen(buff), "line") || lua_pcall(L, 0, 0, 0);
        
        if (errorCode) {
//            fprintf(stderr, "%s", lua_tostring(L, -1));
//            lua_pop(L, 1);
            error(L, "%s", lua_tostring(L, -1));
        }
    }
    
    lua_close(L);
    
    return 0;
}

void error(lua_State *L, const char *fmt, ...)
{
    va_list argp;
    va_start(argp, fmt);
    vfprintf(stderr, fmt, argp);
    va_end(argp);
    lua_close(L);
    std::cout << '\n';
    exit(EXIT_FAILURE);
}

